<!--
 * @Author: 常安民 changanmin1@crdigital.com.cn
 * @Date: 2024-07-26 18:10:50
 * @LastEditors: 常安民 changanmin1@crdigital.com.cn
 * @LastEditTime: 2024-08-06 15:22:52
 * @FilePath: /console-web/src/views/trip/manager/standardPosition/standardPosition.vue
 * @Description: 差标职级管理
 * @email:anmin@foxmail.com
 * Copyright (c) 2024 by 华润数科控股有限公司/常安民, All Rights Reserved. 
-->
<template>
  <!-- 页面-角色管理 -->
  <div class="innerPageTable-out-flex">
    <!-- 搜索区域 -->
    <SelfAdaption>
      <Form
        :model="searchForm"
        ref="searchForm"
        slot="adaption-bar"
        label-position="top"
        class="ivu-form-no-margin-bottom"
        inline
      >
        <template>
          <FormItem prop="travelPositionCode" label="差标职级编码">
            <Input
              type="text"
              :maxlength="30"
              v-model.trim="searchForm['travelPositionCode']"
              placeholder="请输入差标职级编码"
              clearable
              @on-enter="search"
            ></Input>
          </FormItem>
          <FormItem prop="travelPositionName" label="差标职级名称">
            <Input
              type="text"
              :maxlength="30"
              v-model.trim="searchForm['travelPositionName']"
              placeholder="请输入差标职级名称"
              clearable
              @on-enter="search"
            ></Input>
          </FormItem>
          <FormItem prop="tenantCode" label="所属租户" v-if="isPlatformAdmin">
            <Select label-in-value filterable v-model="searchForm.tenantCode" style="width: 100%" clearable>
              <Option v-for="tenant in tenantList" :value="tenant.tenantCode" :key="tenant.id">
                {{ tenant.tenantName }} - {{ tenant.tenantCode }}
              </Option>
            </Select>
          </FormItem>
          <!-- 状态 -->
          <FormItem prop="enabled" :label="$t('common.status')">
            <Select
              style="width: 100%;"
              v-model.trim="searchForm.enabled"
              :placeholder="$t('common.warning.selectStatus')"
              clearable
            >
              <Option v-for="(item, index) in searchStatusList" :value="item.vsiKey" :key="index">{{
                item.vsiValue
              }}</Option>
            </Select>
          </FormItem>
          <!-- 查询\重置按钮 -->
          <FormItem prop="button" class="search-solt-btn">
            <RPButton optType="search" @click="search" />
            <RPButton optType="reset" @click="reset" />
          </FormItem>
        </template>
      </Form>
    </SelfAdaption>
    <InnerPageTable ref="searchTable" :config="tableConfig" v-if="this.userRolePermission || this.appRolePermission">
      <!-- handler bar 查询/重置-->
      <!--
          <div slot="handle-bar">
            <RPButton optType="search" @click="search" />
            <RPButton optType="reset" @click="reset" />
          </div>
          -->
      <!-- table bar 添加-->
      <div slot="table-bar">
        <RPButton optType="create" @click="onOpenAddPage" v-permission="'ROLE_INDEX'" />
        <!--  -->
        <Dropdown @on-click="onDownMenu">
          <Button type="primary">
            批量操作
            <Icon type="ios-arrow-down"></Icon>
          </Button>
          <DropdownMenu slot="list">
            <DropdownItem name="enabled">启用</DropdownItem>
            <DropdownItem name="del">删除</DropdownItem>
            <DropdownItem name="disabled">禁用</DropdownItem>
          </DropdownMenu>
        </Dropdown>
      </div>
    </InnerPageTable>
  </div>
</template>

<script>
import { apiQueryStandardPositionPage, apiStandardPositionBatchOperate } from '@api/trip/standard/standardPosition.js'
import debounce from 'lodash/debounce'

import tenantAPI from '@/api/tenantApi.js'
// import RoleUserListMg from "./RoleUserListManage.vue";
import { searchAppListByTenantCode } from '@/api/applicationApi.js'

import valueSetAPI from '@/api/valueSetAPI.js'
import { CoreModuleName } from '@/const.js'
import { mapGetters } from 'vuex'
export default {
  name: 'trip-standard-position-manager',
  mixins: [],
  data() {
    return {
      title: '差标职级管理',
      category: 1, // 当前登录用户的用户类型
      searchStatusList: [], //状态下拉框数据
      tenantList: [],
      searchForm: {
        // id:"",//
        // tenantCode: $store.state[CoreModuleName].userInfo.tenantCode,//租户编码

        // customerCode:"",//
        // customerName:"",//
        // ouCodes:"",//
        // ouNames:"",//
        // travelPositionCode:"",//职级编码
        // travelPositionName:"",//
        // isApplyBill:"",//是否需要申请单
        // isBudget:"",//是否预算管控
        // createUser:"",//
        // updateUser:"",//
        // updateTime:"",//
        // id:"",
        travelPositionCode: '', // 职级编码(必填)
        travelPositionName: '', // 职级名称(必填)
        customerCode: '', //客户编码
        customerName: '',
        ouCodes: '', // 客商信息
        ouNames: '',
        enabled: '' //是否有效，1有效，0无效
      }
    }
  },
  watch: {},
  computed: {
    ...mapGetters(['isPlatformAdmin']),
    tableConfig() {
      return {
        border: true,
        loadDataFn: this.queryListByPage,
        columnsFn: () => {
          let columns = [
            {
              type: 'selection',
              width: 50,
              align: 'center'
            },
            {
              title: '差标职级编码',
              key: 'travelPositionCode',
              width: 180,
              resizable: true,
              sortable: 'custom',
              render: (h, params) => {
                let title = params.row['travelPositionCode']
                return h(
                  'div',
                  {
                    attrs: {
                      class: 'ivu-table-cell ivu-table-cell-ellipsis',
                      title: title
                    }
                  },
                  title
                )
              }
            },
            {
              title: '差标职级名称',
              key: 'travelPositionName',
              width: 240,
              resizable: true,
              sortable: 'custom',
              render: (h, params) => {
                let title = params.row['travelPositionName']
                return h(
                  'div',
                  {
                    attrs: {
                      class: 'ivu-table-cell ivu-table-cell-ellipsis',
                      title: title
                    }
                  },
                  title
                )
              }
            },
            {
              title: '所属租户',
              key: 'tenantCode',
              align: 'center',
              width: 240,
              resizable: true,
              sortable: 'custom',
              render: (h, params) => {
                let title = this.tenantByName[params.row['tenantCode']] + `(${params.row['tenantCode']})`
                return h(
                  'div',
                  {
                    attrs: {
                      class: 'ivu-table-cell ivu-table-cell-ellipsis',
                      title: title
                    }
                  },
                  title
                )
              }
            },
            {
              title: '归属公司',
              key: 'ouNames',
              align: 'center',
              resizable: true,
              sortable: 'custom',
              render: (h, params) => {
                let title = params.row['ouNames']
                return h(
                  'div',
                  {
                    attrs: {
                      class: 'ivu-table-cell ivu-table-cell-ellipsis',
                      title: title
                    }
                  },
                  title
                )
              }
            },
            {
              title: '关联的差标',
              key: 'travelStandardName',
              align: 'center',
              resizable: true,
              width: 200,
              render: (h, params) => {
                let title = params.row['travelStandardName']
                return h(
                  'div',
                  {
                    attrs: {
                      class: 'ivu-table-cell ivu-table-cell-ellipsis',
                      title: title
                    }
                  },
                  title
                )
              }
            }, 
            {
              title: this.$t('common.status'),
              align: 'center',
              key: 'enabled',
              width: 100,
              render: (h, params) => {
                return h(
                  'StatusButton',
                  {
                    // 修改StatusButton内容居中
                    style: {
                      'justify-content': 'center'
                    },
                    props: {
                      status: params.row.enabled == '1' ? '0' : '1'
                    }
                  },
                  params.row.enabled == '1' ? this.$t('common.enable') : this.$t('common.disable')
                )
              }
            },
            {
              title: '更新时间',
              key: 'updateTime',
              align: 'center',
              resizable: true,
              width: 160,
              render: (h, { row: { updateUser, updateTime } }) => {
                let txt = updateUser && updateTime ? `${updateTime}(${updateUser})` : ''
                return h(
                  'div',
                  {
                    attrs: {
                      class: 'ivu-table-cell ivu-table-cell-ellipsis',
                      title: txt
                    }
                  },
                  txt
                )
              }
            },
            {
              title: '创建时间',
              key: 'createTime',
              align: 'center',
              resizable: true,
              width: 220,
              render: (h, { row: { createUser, createTime } }) => {
                let txt = createUser && createTime ? `${createTime}(${createUser})` : ''
                return h(
                  'div',
                  {
                    attrs: {
                      class: 'ivu-table-cell ivu-table-cell-ellipsis',
                      title: txt
                    }
                  },
                  txt
                )
              }
            },
            {
              title: this.$t('common.operating'),
              align: 'left',
              fixed: 'right',
              resizable: true,
              width: 150,
              render: (h, { row }) => {
                let data = []
                if (row.enabled == '1') {
                  data = [
                    {
                      text: '编辑',
                      handle: debounce(() => this.onOpenEditPage(row), 300)
                    },
                    {
                      text: '禁用',
                      handle: debounce(() => this.onUpdate(row, 0), 300)
                    }
                  ]
                } else {
                  data = [
                    {
                      text: '编辑',
                      handle: debounce(() => this.onOpenEditPage(row), 300)
                    },
                    {
                      text: '启用',
                      handle: debounce(() => this.onUpdate(row, 1), 300)
                    },
                    {
                      text: '删除',
                      handle: debounce(() => this.onDel(row), 300)
                    }
                  ]
                }
                return h('RowTools', {
                  props: {
                    data: data
                  }
                })
              }
            }
          ]
          if (!this.isPlatformAdmin) {
            columns = columns.filter(item => {
              if (item.key == 'tenantCode') {
                return false
              }
              return true
            })
          }
          return columns
        },
        autoFirst: false,
        rowClassNameFn: this.rowClassName // 自定义行样式
      }
    },
    userRolePermission() {
      if ($store.state['ripples-components'].resList) {
        return $util.checkPermission('TRIP-POSITION-MANAGER-INDEX')
      }
    },
    appRolePermission() {
      if ($store.state['ripples-components'].resList) {
        return $util.checkPermission('TRIP-POSITION-MANAGER-INDEX')
      }
    },
    tenantByName() {
      let tenantCodes = {}
      this.tenantList.map(item => {
        tenantCodes[item.tenantCode] = item.tenantName
      })
      return tenantCodes
    }
  },
  created: function() {
    this.getStateSelect()
    this.tenantList = []
  },
  mounted() {
    if (this.isPlatformAdmin) {
      // 平台管理员可以搜索租户信息
      this.$set(this.searchForm, 'tenantCode', '')
      /**
       * 加载所有租户
       */
      tenantAPI.queryTenantList().then(data => {
        // const {tenantName ,tenantCode,id }
        this.tenantList = data
      })
    }
    this.init()
  },
  methods: {
    /**
     * 获取表格中选择的行ID
     */
    getSelectedIds() {
      let list = this.$refs['searchTable'].getSelectioned() || []
      let ids = []
      for (let u of list) {
        ids.push(u.id)
      }
      return ids
    },
    onDownMenu(name) {
      let ids = this.getSelectedIds();
      if (ids.length > 0) {
        const confirmMessages = {
          'enabled': '您确定要启用所选择的差标职级数据吗？',
          'disabled': '您确定要禁用所选择的差标职级数据吗？',
          'del': '您确定要删除所选择的差标职级数据吗？'
        };

        const successMessages = {
          'enabled': '启用成功',
          'disabled': '禁用成功',
          'del': '删除成功'
        };

        const enabledValues = {
          'enabled': '1',
          'disabled': '0',
          'del': '2'
        };

        if (confirmMessages[name] && enabledValues[name]) {
          new $confirm(confirmMessages[name], this).then(() => {
            this.performBatchOperate(ids, enabledValues[name])
              .then(() => {
                this.$message.success({
                  content: successMessages[name],
                  duration: 3
                });
                this.search();
              })
              .catch(data => {
                this.$message.error({
                  content: data.message,
                  duration: 3
                });
              });
          });
        }
      }
    },

    performBatchOperate(ids, enabledValue) {
      return apiStandardPositionBatchOperate({ ids: ids.join(','), enabled: enabledValue });
    },
    // 自定义行样式
    rowClassName(row) {
      //关联的菜单中是否存在有效的hasEnabledMenu:1-存在,0-不存在。enabled:1-有效，0-无效。roleType：1-用户角色，2-应用角色
      if (row.hasEnabledMenu == 0 && row.enabled == 1 && row.roleType == 1) {
        return 'tableDisableStyle'
      }
    },
    // 获取状态下拉数据
    async getStateSelect() {
      const [searchStatusList = []] = await Promise.all([valueSetAPI.getValueSetByCode('ENABLED_CODE')])
      searchStatusList.map((item, index) => {
        if (item.vsiKey == 'ALL') {
          searchStatusList.splice(index, 1)
        }
      })
      this.searchStatusList = searchStatusList
    },
    async init() {
      let { userInfo } = $store.state[CoreModuleName]
      if (!userInfo) return
      this.category = userInfo.category
      // 根据当前租户查询数据
      // this.searchForm.tenantCode = userInfo.tenantCode
      const [appData] = await Promise.all([
        // valueSetAPI.getValueSetByCode('ROLE_TYPE'),
        searchAppListByTenantCode({
          pageNum: 1,
          pageSize: 200,
          condition: {
            tenantCode: userInfo.tenantCode
          }
        })
      ])
      console.log('appData :>> ', appData)
      // 查询列表
      this.search()
    },

    search(page = 1) {
      let searchParams = Object.assign({}, this.searchForm)
      this.$refs['searchTable'].load(searchParams, page)
    },
    /**
     * 重置搜索表单并重新执行搜索
     *
     * 重置搜索表单字段，并将搜索页码设为1，然后执行搜索操作。
     */
    reset() {
      // 检查searchForm引用是否存在
      if (this.$refs['searchForm'] && typeof this.$refs['searchForm'].resetFields === 'function') {
        // 重置搜索表单字段
        this.$refs['searchForm'].resetFields();
    
        // 检查search方法是否存在
        if (typeof this.search === 'function') {
          // 执行搜索，页码为1
          this.search(1);
        } else {
          console.error('The search method does not exist.');
        }
      } else {
        console.error('The searchForm reference does not exist or resetFields is not a function.');
      }
    },
    /**
     * 更新行数据状态函数
     *
     * @param row 需要更新的行数据对象
     * @param enabled 状态值，1表示启用，非1表示禁用
     */
    onUpdate(row, enabled) {
      let title = enabled == 1 ? '启用' : '禁用'
      new $confirm('您确定要' + title + '该行差标职级数据吗？', this).then(() => {
        // enabled 0 禁用
        apiStandardPositionBatchOperate({ ids: row.id + '', enabled: enabled + '' })
          .then(res => {
            this.$message.success({
              content: '修改成功',
              duration: 3
            })
            this.search()
          })
          .catch(data => {
            this.$message.error({
              content: data.message,
              duration: 3
            })
          })
      })
    },
    onDel(row) {
      new $confirm('您确定要删除该行差标职级数据吗？', this).then(() => {
        apiStandardPositionBatchOperate({ ids: row.id + '', enabled: '2' })
          .then(res => {
            this.$message.success({
              content: this.$t('module.orgManage.deleteSuccess'),
              duration: 3
            })
            this.search()
          })
          .catch(data => {
            this.$message.error({
              content: data.message,
              duration: 3
            })
          })
      })
    },
    onOpenEditPage(row) {
      new this.$sidelipPage(
        () => import('./standardPositionDetail.vue'),
        {
          props: {
            StandardPosition: Object.assign({},row),
            disabled:false,
          },
          isActionTop: false
        },
        data => {
          data && this.search()
        }
      )
    },
    onOpenAddPage: debounce(function() {
      new this.$sidelipPage(
        () => import('./standardPositionDetail.vue'),
        {
          props: { 
            disabled: false
          },
          isActionTop: false
        },
        data => {
          data && this.search()
        }
      )
    }, 300),

    queryListByPage({ responseProcess, param }) {
      console.log('param :>> ', param)
      return apiQueryStandardPositionPage(param).then(data => {
        console.log('data :>> ', data)
        if (data.success) {
          responseProcess(data.data)
        } else {
          this.$message.error({
            content: data.message || '未查询到差标职级信息',
            duration: 3
          })
          responseProcess({ records: [] })
        }
      })
    }
  }
}
</script>

<style></style>
